//
//  SelectInviterViewController.m
//  PigMarket
//
//  Created by Felix on 2019/3/13.
//  Copyright © 2019 felix.pigmarket.oc. All rights reserved.
//

#import "SelectInviterViewController.h"

#import "SelectInviterHeaderView.h"
#import "SelectInviterCell.h"
#import "PrefectPersonalInfoViewController.h"
#import "InviteTipsAlertView.h"

#import "LoginGuideView.h"


@interface SelectInviterViewController ()<UITableViewDelegate,UITableViewDataSource>

/**
 headerView
 */
@property (nonatomic , strong) SelectInviterHeaderView *headerView;

/**
 inviterTableView
 */
@property (nonatomic , strong) UITableView *inviterTableView;
/**
 dataArr
 */
@property (nonatomic , strong) NSMutableArray *dataArr;
/**
 邀请提示自定义弹框view
 */
@property (nonatomic , strong) InviteTipsAlertView *contentAlertView;

@property (nonatomic, strong) LoginGuideView *guideView;


@end

@implementation SelectInviterViewController

#pragma mark - view life cycle
- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.baseNavView.navTitleLabel.text = @"选择邀请人";
    [self setupNav];
    [self setUpView];
    
    if ([self isFirstLoad]) {
        [self.guideView show];
    }
}

-(void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
}

-(void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
}

#pragma mark - init method

- (void)setupNav {
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamed:@"register_selectInviter_help"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStylePlain target:self action:@selector(helpTapped)];
}
- (void)setUpView {
    [self initView];
    [self initLayout];
    [self initAction];
    [self initData];
}
- (void)initView {
    [self.view addSubview:self.headerView];
    [self.view addSubview:self.inviterTableView];
}

- (void) initLayout {
    [self.headerView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_equalTo(0);
        make.top.mas_equalTo(TJ_NavBarHeight);
    }];
    [self.inviterTableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.headerView.mas_bottom);
        make.left.right.bottom.mas_equalTo(0);
    }];
}
- (void) initAction {
    [self.headerView.nextBtn addTarget:self action:@selector(nextTapped) forControlEvents:UIControlEventTouchUpInside];
}
- (void)initData {
    //定位信息
    @weakify(self);
    [[LocationManager sharedManager] startLocationCompleteBlock:^(double latitude, double longitude) {
        @strongify(self);
        if (latitude && longitude) {
            NSString *lat = [NSString stringWithFormat:@"%f",latitude];
            NSString *longi = [NSString stringWithFormat:@"%f",longitude];

            [self getInviterListRequestWithLatitude:lat longitude:longi];
        }
    }];
}
 //获取邀请人列表
- (void)getInviterListRequestWithLatitude:(NSString *)latitude longitude:(NSString *)longitude {
   
    @weakify(self);
    [[[PigMarketApi sharedInstance] getSelectInviterListWithLongitude:longitude latitude:latitude] subscribeNext:^(SelectInviterList * _Nullable selectInviterList) {

        @strongify(self);
        [self.dataArr addObjectsFromArray:selectInviterList.inviterList];
        [self.inviterTableView reloadData];
    } error:^(NSError * _Nullable error) {
        
        @strongify(self);
        [self handlingError:error];
    }];
}


//输入邀请码下一步数据请求
- (void)inviteRequest{
    NSString *code = self.headerView.inviteCodeField.text;
    
    NSString *account = [UserInfoDataProvider sharedInstance].userInfo.phone;
    
    if ([code isBlankString]) {
        [self toastWithContent:@"请输入邀请码"];
        return;
    }
    @weakify(self);
    [[[PigMarketApi sharedInstance] userSelectInviteCodeWithCode:code account:account] subscribeNext:^(NSNull * _Nullable x) {
        @strongify(self);
        PrefectPersonalInfoViewController *personalInfoVC = [[PrefectPersonalInfoViewController alloc] init];
        personalInfoVC.title = PrefectPersonalInfoTitle;
        [self.navigationController pushViewController:personalInfoVC animated:YES];
    } error:^(NSError * _Nullable error) {
        @strongify(self);
        [self handlingError:error];
    }];
}
//选择邀请人请求
- (void)inviteRequestWithSelectInviteCode:(NSString *)inviteCode {
    
    NSString *account = [UserInfoDataProvider sharedInstance].userInfo.phone;
    
    if ([inviteCode isBlankString]) return;
    @weakify(self);
    [[[PigMarketApi sharedInstance] userSelectInviteCodeWithCode:inviteCode account:account] subscribeNext:^(NSNull * _Nullable x) {
        @strongify(self);
        PrefectPersonalInfoViewController *personalInfoVC = [[PrefectPersonalInfoViewController alloc] init];
        personalInfoVC.title = PrefectPersonalInfoTitle;
        [self.navigationController pushViewController:personalInfoVC animated:YES];
    } error:^(NSError * _Nullable error) {
        @strongify(self);
        [self handlingError:error];
    }];
}
#pragma mark - delegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataArr.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    SelectInviterCell *cell = [SelectInviterCell cellWithTableView:tableView];
    if (self.dataArr.count > 0 && self.dataArr.count > indexPath.row) {
        SelectInviter *model = self.dataArr[indexPath.row];
        cell.selectInviter = model;
        
        @weakify(self);
        [cell setSelectInviterBlock:^{//选择他
            @strongify(self);
            [self selectInviterWithModel:model];
        }];
    }
    return cell;
}

#pragma mark - target action
- (void)selectInviterWithModel:(SelectInviter *)model {
    //选择他
    [self.contentAlertView.headImg sd_setImageWithURL:[NSURL URLWithString:model.headImg] placeholderImage:[UIImage imageNamed:@"placeholder_header"]];
    self.contentAlertView.nameLab.text = model.name;
    self.contentAlertView.idLab.text = [NSString stringWithFormat:@"ID:%@",model.memberNum];
    @weakify(self);
    [self alertViewWithTitle:@"邀请提示" contentView:self.contentAlertView btnTitle:@"确定" btnBlock:^{
        @strongify(self);
        [self inviteRequestWithSelectInviteCode:model.memberNum];
    }];
}
- (void)nextTapped {
    [self inviteRequest];
}
- (void)helpTapped {
    [self alertViewWithTitle:@"豚集陪您一起赚钱" content:@"选择身边适合自己的邀请人，可获得一对一的优质体验服务，掌握平台最新最全的优惠信息；玩转豚集平台，分享轻松赚钱。" btnTitle:@"确定" btnBlock:nil];
}
#pragma mark - private method

#pragma mark - getter and setter

- (SelectInviterHeaderView *)headerView {
    if (!_headerView) {
        _headerView = [[SelectInviterHeaderView alloc] init];
        _headerView.backgroundColor = [UIColor colorWithHexString:@"#f7f7f7"];
    }
    return _headerView;
}

- (InviteTipsAlertView *)contentAlertView {
    if (!_contentAlertView) {
        _contentAlertView = [[InviteTipsAlertView alloc] init];
    }
    return _contentAlertView;
}

- (UITableView *)inviterTableView {
    if (!_inviterTableView) {
        _inviterTableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
        _inviterTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _inviterTableView.rowHeight = 100;
        _inviterTableView.dataSource = self;
        _inviterTableView.delegate = self;
        _inviterTableView.tableFooterView = [[UIView alloc] init];
    }
    return _inviterTableView;
}

- (LoginGuideView *)guideView{
    
    if (!_guideView) {
        _guideView = [[LoginGuideView alloc] init];
        
        NSMutableAttributedString *string = [[NSMutableAttributedString alloc] initWithString:@"选择邀请人/填写邀请码，可再得50元（豚券）"attributes: @{NSFontAttributeName: [UIFont fontWithName:@"PingFangSC-Regular" size: 14],NSForegroundColorAttributeName: [UIColor colorWithRed:83/255.0 green:83/255.0 blue:83/255.0 alpha:1.0]}];
        
        [string addAttributes:@{NSForegroundColorAttributeName: [UIColor colorWithRed:83/255.0 green:83/255.0 blue:83/255.0 alpha:1.000000]} range:NSMakeRange(0, 15)];
        
        [string addAttributes:@{NSForegroundColorAttributeName: [UIColor colorWithRed:242/255.0 green:92/255.0 blue:98/255.0 alpha:1.000000]} range:NSMakeRange(15, 3)];
        
        [string addAttributes:@{NSForegroundColorAttributeName: [UIColor colorWithRed:83/255.0 green:83/255.0 blue:83/255.0 alpha:1.000000]} range:NSMakeRange(18, 4)];

        
        _guideView.attributedStr = string;
    }
    return _guideView;
}


- (NSMutableArray *)dataArr {
    if (!_dataArr) {
        _dataArr = [[NSMutableArray alloc] init];
    }
    return _dataArr;
}

@end
